#include "centralwidgetcontainer.h"
#include <QPainter>

using namespace ExecTerminalImplNS;

const int TOP_WIDGET_MARGIN = 1;
const int LEFT_WIDGET_MARGIN = 0;
const int RIGHT_WIDGET_MARGIN = 2;
const int BOTTOM_WIDGET_MARGIN = 1;
const QColor MIDDLE_COLOR(227, 226, 226);
const QColor DARK_COLOR(153, 153, 153);

CentralWidgetContainer::CentralWidgetContainer(QWidget * parent): QWidget(parent),
thePosition(RIGHT_POSITION)
{
    QWidget * centralW = new QWidget(this);
    centralW->setAutoFillBackground(true);
    centralW->setBackgroundRole(QPalette::Base);
    layoutCentralWidget();
}

QWidget * CentralWidgetContainer::centralWidget()const
{
    if (!children().isEmpty())
    {
        QObject * child = children().first();
        Q_ASSERT(child->isWidgetType());
        return static_cast<QWidget *>(child);
    }
    return 0;
}

void CentralWidgetContainer::setCentralWidget(QWidget * w)
{
    if (w != centralWidget())
    {
        delete centralWidget();
        w->setParent(this);
        layoutCentralWidget();
    }
}

void CentralWidgetContainer::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    const int bottomLineY = height() - 1;
    const bool isNormalDirection = thePosition == RIGHT_POSITION;
    
    const int lineX = isNormalDirection ? width() - 1 : 0;
    painter.setPen(MIDDLE_COLOR);
    painter.drawLine(0, bottomLineY, width() - 2, bottomLineY);

    const int xOffset = isNormalDirection ? -1 : +1;
    painter.drawLine(lineX + xOffset, TOP_WIDGET_MARGIN, lineX + xOffset, bottomLineY - 1);

    painter.setPen(DARK_COLOR);
    painter.drawLine(lineX, TOP_WIDGET_MARGIN, lineX, bottomLineY);

    const QColor & rectCol = palette().base().color();
    painter.fillRect(QRect(0, 0, width(), TOP_WIDGET_MARGIN), rectCol);
}

void CentralWidgetContainer::resizeEvent(QResizeEvent *)
{
    layoutCentralWidget();
}

void CentralWidgetContainer::layoutCentralWidget()
{
    QWidget * centrWidget = centralWidget();
    if (centrWidget)
    {
        const bool isNormalDirection = thePosition == RIGHT_POSITION;
        centrWidget->setGeometry(isNormalDirection ? LEFT_WIDGET_MARGIN : RIGHT_WIDGET_MARGIN, 
        TOP_WIDGET_MARGIN, 
        width() - LEFT_WIDGET_MARGIN - RIGHT_WIDGET_MARGIN,
        height() - TOP_WIDGET_MARGIN - BOTTOM_WIDGET_MARGIN);
    }
}

void CentralWidgetContainer::setPosition(Position pos)
{
    if (thePosition != pos)
    {
        thePosition = pos;
        layoutCentralWidget();
        update();
    }
}

void CentralWidgetContainer::switchPosition()
{
    switch(thePosition)
    {
    case LEFT_POSITION:
        setPosition(RIGHT_POSITION);
    	break;
    case RIGHT_POSITION:
        setPosition(LEFT_POSITION);
    default:
        break;
    }
}




